package com.elai.analytics.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.elai.analytics.domain.*;
import com.elai.analytics.domain.third.CkOverviewItemReq;
import com.elai.analytics.service.TouchModeService;
import com.elai.baseconfig.domain.EventItemDO;
import com.elai.baseconfig.service.EventItemService;
import com.elai.common.annotation.Log;
import com.elai.common.constant.BusinessConstants;
import com.elai.common.core.controller.BaseController;
import com.elai.common.core.domain.AjaxResult;
import com.elai.common.enums.BusinessType;
import com.elai.common.utils.DateUtils;
import com.elai.common.utils.ThirdProperties;
import com.elai.common.utils.WebUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 *事件分析
 * @author elai
 * @date 2021-04-04
 */
@RestController
@RequestMapping("/event/base")
public class EventController extends BaseController
{

    private static final Logger log = LoggerFactory.getLogger(EventController.class);
    @Autowired
    private ThirdProperties thirdProperties;

    @Autowired
    private EventItemService eventItemService;
 //   @Autowired
//    private TouchModeService touchModeService;

    //事件分析
    private static final String EVENTANALYSIS ="event/findEvent";

    //同比
    private  final  static  String ONYEARFLOW="01";
    //环比
    private  final  static  String COMPARISON="02";


    //事件分析
    @Log(title = "事件分析", businessType = BusinessType.OTHER)
    @PostMapping("/eventAnalyzeCharData")
    public AjaxResult eventAnalyzeCharData(@RequestBody String requestJson)
    {
        log.info("eventAnalyzeCharData："+requestJson);
        JSONObject paramJson = JSONObject.parseObject(requestJson);
        JSONObject eventJson = requestJson.isEmpty()?new JSONObject(): paramJson.getJSONObject("requestJson");
        if (JSONUtil.isNull(eventJson)){
            eventJson = new JSONObject();
        }

        String pageNum = eventJson.getString("pageNum");
        JSONArray applicationCodeArray = eventJson.getJSONArray("applicationCode");
        JSONArray comparisonDateRangeArray = eventJson.getJSONArray("comparisonDateRange");
        JSONArray dateRangeArray = eventJson.getJSONArray("dateRange");
        String combine = eventJson.getString("combine");
        String pageSize = eventJson.getString("pageSize");
        String timeType = eventJson.getString("timeType");
        String statisticsType = eventJson.getString("statisticsType");
        int chartType = eventJson.containsKey("chartType")?eventJson.getInteger("chartType"):1;
        JSONArray queryItemsArray = eventJson.containsKey("queryItems")?eventJson.getJSONArray("queryItems"):new JSONArray();
//        System.out.println(queryItemsArray);
        JSONArray filterTagsArray = eventJson.getJSONArray("filterTags");

        String startDate = null;
        String endDate = null;
        if (JSONUtil.isNull(dateRangeArray)){
            startDate = DateUtils.getYYYYMMDD(-6);
            endDate = DateUtils.getYYYYMMDD(-1);
        }else{
            String tempStartDate = dateRangeArray.getString(0);
            String tempEndDate = dateRangeArray.getString(1);
            startDate = tempStartDate.length()>10?tempStartDate.substring(0,10):tempStartDate;
            endDate = tempEndDate.length()>10?tempEndDate.substring(0,10):tempEndDate;
        }

//        QueryParam queryParam=new QueryParam();
//        List<Map<String,Object>> filterTags=queryParam.getFilterTags();
        Map<String,Object> resultMap=new HashMap();
        String charType="line";
        if(chartType==1 || chartType==4){
            charType="line";
        }else if(chartType==2){
            charType="bar";
        }
        List chartData=new ArrayList();
        //报表的表头
        List<String> title=new ArrayList<String>();
        //表格的表头
        List<ColumnHeader> tableTitle=new ArrayList<ColumnHeader>();
        tableTitle.add(new ColumnHeader("eventName","指标","",false));
        tableTitle.add(new ColumnHeader("total","合计","",false));
//        if(filterTags!=null && filterTags.size()>0) {
//            filterTags.stream().forEach(t -> {
//                tableTitle.add(new ColumnHeader(t.get("eventTypeName")+"",t.get("eventTypeName")+"","",false));
//            });
//        }

        String startContrastDate="";
        String endContrastDate="";
        if(comparisonDateRangeArray!=null&&comparisonDateRangeArray.size()>0){
            startContrastDate=comparisonDateRangeArray.getString(0);
            endContrastDate=comparisonDateRangeArray.getString(1);
        }

        List<String> dateList= DateUtils.getBetweenDates(startDate,endDate);
        for (String  s:dateList){
            title.add(s);
            tableTitle.add(new ColumnHeader(s,s,"",true));
        }

        Map<String, Object> paramMap =new HashedMap();
        paramMap.put("startDate",startDate);
        paramMap.put("endDate",endDate);
        paramMap.put("combine",combine);

        paramMap.put("startContrastDate",startContrastDate);
        paramMap.put("endContrastDate",endContrastDate);
        paramMap.put("applicationCodeArray",applicationCodeArray);
        if (applicationCodeArray != null && !applicationCodeArray.isEmpty()){
            paramMap.put("applicationCodeList",applicationCodeArray.toJavaList(String.class));
        }
        paramMap.put("jsonParam",eventJson);

        List<Map<String,Object>> tableData=new ArrayList<>();
        List<CkOverviewItemReq> itemMapList = new ArrayList<>();
        Map<String,String> eventMap = new HashMap<>();
        if (queryItemsArray != null){
            for(int j=0;j<queryItemsArray.size();j++){
                CkOverviewItemReq itemMap =new CkOverviewItemReq();
                JSONObject outJson= JSONObject.parseObject(queryItemsArray.getString(j));
                JSONArray eventMethodArray = outJson.getJSONArray("eventMethod");
                itemMap.setIsInt("N");
                if(eventMethodArray!=null){
                    if (eventMethodArray.size() == 2){
                        itemMap.setMethodName(eventMethodArray.getString(1));
                        itemMap.setFieldName(eventMethodArray.getString(0));

                        EventItemDO eventItem = new EventItemDO();
                        eventItem.setEventItemCode(eventMethodArray.getString(0));
                        eventItem.setValueType(BusinessConstants.value_type_int);
                        List<EventItemDO> codeList = eventItemService.selectEventItemList(eventItem);
                        if (codeList != null && codeList.size() > 0){
                            itemMap.setIsInt("Y");
                        }
                    }else{
                        itemMap.setMethodName(eventMethodArray.getString(0));
                    }

                }
                itemMap.setEventName(outJson.getString("eventType"));
                itemMap.setCategoryType(outJson.getString("categoryType"));
                itemMap.setJsonParam(outJson);

                itemMapList.add(itemMap);
                eventMap.put(outJson.getString("eventType"),outJson.getString("typeName"));

            }
        }


        paramMap.put("eventItemList",itemMapList);
        List<OvervivwResVO> resVOList=new ArrayList<>();

        JSONObject obj=WebUtils.postCkObj(thirdProperties.getCkUrl(),EVENTANALYSIS,paramMap);
        if (obj != null){
            String subcode = obj.getString("code");
            if("0".equals(subcode)){
                resVOList = JSON.parseArray(obj.getString("data"), OvervivwResVO.class);
            }
        }

        for (OvervivwResVO resVO : resVOList) {
            String eventType = resVO.getEventName();
            List<OvervivwVO> overvivwList = resVO.getOvervivwList();
            List<BigDecimal> trTotals = new ArrayList<>();
            overvivwList.forEach(o -> {
                o.setEventCount((new BigDecimal(o.getEventCount()).setScale(2,BigDecimal.ROUND_HALF_UP)).toString());
                trTotals.add(new BigDecimal(o.getEventCount()));
            });
            BigDecimal trTotal = trTotals.stream().reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
            trTotal = trTotal.setScale(2,BigDecimal.ROUND_HALF_UP);

            Map<String,Object> data = new HashMap<>();
            for(ColumnHeader t:tableTitle){
                Map cellData = new HashMap();
                if("指标".equals(t.getColumnLabel())){
                    cellData.put("data",eventMap.get(eventType));
                    cellData.put("comparison", "");
                }
                else if ("total".equals(t.getColumnName())){
                    cellData.put("data",trTotal);
                    cellData.put("comparison", "");
                }
                else {
                    String [] is=getInt(t.getColumnName(),overvivwList,combine);
                    cellData.put("data", is[0]);
                    cellData.put("comparison", is[1]);
                }
                data.put(t.getColumnName(), cellData);
            }
            tableData.add(data);

            List<BigDecimal> data1=new ArrayList<>();
            for(String t:title){
                data1.add(new BigDecimal(getInt(t,overvivwList,combine)[0]));
            }
            //显示图表
            Map<String,Object> dataMap1=new HashMap();
            dataMap1.put("name",eventMap.get(eventType));
            if(chartType==1 || chartType==2  || chartType==4){
                dataMap1.put("type",charType);
                dataMap1.put("data",data1);
            }
            if(chartType==2){
                dataMap1.put("stack","vistors");
                dataMap1.put("barWidth","80%");
            }
            else if(chartType==3){
                BigDecimal sum = data1.stream().reduce((a,b)->a.add(b)).get() ;
                dataMap1.put("value",sum);
            }
            else if(chartType==4){
                dataMap1.put("areaStyle",new HashMap());
                dataMap1.put("emphasis",new HashMap().put("focus","series"));
            }
            chartData.add(dataMap1);
        }

        resultMap.put("chartData",chartData);
        resultMap.put("chartTitle",title);
        resultMap.put("tableTitle",tableTitle);
        resultMap.put("tableData",tableData);
        return AjaxResult.success(resultMap);
    }

    @PostMapping("/OverviewCharData")
    public AjaxResult OverviewCharData(@RequestBody String requestJson)
    {
        Integer code1 = (int) ((Math.random() * 9 + 1) * 100);
        Integer code2 = (int) ((Math.random() * 9 + 1) * 100);
        Integer code3 = (int) ((Math.random() * 9 + 1) * 100);
        Integer code4 = (int) ((Math.random() * 9 + 1) * 100);
        Integer code5 = (int) ((Math.random() * 9 + 1) * 100);
        Map<String,Object> resultMap=new HashMap();
        List<Object> chartData=new ArrayList<>();
        Map data=new HashMap();
        data.put("name","邮件营销");
        data.put("type","line");
        data.put("stack","总量");
        data.put("data",new Integer[]{120, code1, 101, code3, 90, 230, code5});
        data.put("smooth", false);
        chartData.add(data);

        Map data1=new HashMap();
        data1.put("name","联盟广告");
        data1.put("type","line");
        data1.put("stack","总量");
        data1.put("data",new Integer[]{320, code2, 301, code4, 390, 330, code5});
        data1.put("smooth", false);
        chartData.add(data1);

        Map data2=new HashMap();
        data2.put("name","视频广告");
        data2.put("type","line");
        data2.put("stack","总量");
        data2.put("data",new Integer[]{code1, 932, code2, 934, code3, 1330, code4});
        data2.put("smooth", false);
        chartData.add(data2);


        resultMap.put("chartData",chartData);

        List<String> titleData=new ArrayList<>();
        titleData.add("周一");
        titleData.add("周二");
        titleData.add("周三");
        titleData.add("周四");
        titleData.add("周五");
        titleData.add("周六");
        titleData.add("周日");
        resultMap.put("chartTitle",titleData);


        List<String> legendData=new ArrayList<>();
        legendData.add("邮件营销");
        legendData.add("联盟广告");
        legendData.add("视频广告");
        resultMap.put("chartLegend",legendData);

        Map viewData=new HashMap();

        viewData.put("data1",code1);
        viewData.put("data2",code2);
        viewData.put("data3",code3);
        viewData.put("data4",code4);
        viewData.put("data5",code5);
        resultMap.put("viewData",viewData);


        return AjaxResult.success(resultMap);
    }

    private   String []  getInt(String t,List<OvervivwVO> overvivwVOList,String combine){
        String []  b={"0","0"};
        for (OvervivwVO vo:overvivwVOList){
            if(t.equals(vo.getEventDate())){
                b[0]=vo.getEventCount();
                b[1]=vo.getCombineCount()+"";
                break;
            }
        }
        return b;
    }

}
